<?php

namespace app\controllers;

use app\librarys\Fanso2oInteface;
use app\librarys\Inteface;
use app\librarys\Tools;
use app\models\Institution;
use app\models\LoginForm;
use app\models\Manager;
use app\models\Menu;
use yii\web\Controller;

class SiteController extends Controller
{
    public $layout = false;
    public $enableCsrfValidation = false;

//    public function behaviors()
//    {
//        return [
//            'access' => [
//                'class' => AccessControl::className(),
//                'only' => ['logout'],
//                'rules' => [
//                    [
//                        'actions' => ['logout'],
//                        'allow' => true,
//                        'roles' => ['@'],
//                    ],
//                ],
//            ],
//            'verbs' => [
//                'class' => VerbFilter::className(),
//                'actions' => [
//                    'logout' => ['post'],
//                ],
//            ],
//        ];
//    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
//            'captcha' => [
//                'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//            ],
        ];
    }


    private function _isMobile()
    {
        $useragent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        echo $useragent . '<br>';
        $useragent_commentsblock = preg_match('|.∗?|', $useragent, $matches) > 0 ? $matches[0] : '';
        echo $useragent_commentsblock . '<br>';

        function CheckSubstrs($substrs, $text)
        {
            foreach ($substrs as $substr)
                if (false !== strpos($text, $substr)) {
                    return true;
                }
            return false;
        }

        $mobile_os_list = array('Google Wireless Transcoder', 'Windows CE', 'WindowsCE', 'Symbian', 'Android', 'armv6l', 'armv5',
            'Mobile', 'CentOS', 'mowser', 'AvantGo', 'Opera Mobi', 'J2ME/MIDP', 'Smartphone', 'Go.Web', 'Palm', 'iPAQ');
        $mobile_token_list = array('Profile/MIDP', 'Configuration/CLDC-', '160×160', '176×220', '240×240', '240×320', '320×240',
            'UP.Browser', 'UP.Link', 'SymbianOS', 'PalmOS', 'PocketPC', 'SonyEricsson', 'Nokia', 'BlackBerry', 'Vodafone', 'BenQ', 'Novarra-Vision',
            'Iris', 'NetFront', 'HTC_', 'Xda_', 'SAMSUNG-SGH', 'Wapaka', 'DoCoMo', 'iPhone', 'iPod', 'MicroMessenger', 'MiuiBrowser', 'MQQBrowser');

        $found_mobile = CheckSubstrs($mobile_os_list, $useragent_commentsblock) ||
            CheckSubstrs($mobile_token_list, $useragent);

        if ($found_mobile) {
            return true;
        } else {
            return false;
        }
    }

    public function actionIndex()
    {
        $institutionDomain = explode('://', \Yii::$app->request->hostInfo)[1];
        $currentInstitution = Institution::getInstitutionByDomain($institutionDomain);
        if ($currentInstitution != null) {
            if ($this->_isMobile()) {
                return $this->redirect('mall-m/index');
            } else {
//                return $this->redirect('mall/index');
                return $this->redirect('mall-m/index');
            }
        }
        return $this->redirect('site/login');
//        return $this->render('index');
    }

    public function actionLogin()
    {
        $model = new LoginForm();
        $redirectUrl = \Yii::$app->request->get('redirect_url');
        if ($model->load(\Yii::$app->request->post()) && $model->login()) {
            if (empty($redirectUrl)) {
                $indexPhp = \Yii::$app->urlManager->showScriptName ? '/index.php' : '';

                // 找出当前登录管理员权限所能访问的第一个页面
                $url = '/dashboard/index';
                $menus = Menu::getAllMenus();
                foreach ($menus as $menu) {
                    if (isset($menu['sub_menu_list'])) {
                        if (count($menu['sub_menu_list']) > 0) {
                            $url = '/' . $menu['sub_menu_list'][0]['controller'] . '/' . $menu['sub_menu_list'][0]['action'];
                        }
                    } else {
                        $url = '/' . $menu['controller'] . '/' . $menu['action'];
                    }
                    break;
                }

                $redirectUrl = \Yii::$app->request->baseUrl . $indexPhp . $url;
            }
            return $this->redirect($redirectUrl);
        }
        return $this->render('login', [
            'model' => $model,
            'redirect_url' => $redirectUrl
        ]);
    }

    public function actionLogout()
    {
        Manager::logout();
        return $this->redirect('login');
    }

    public function actionAbout()
    {
        return $this->render('about');
    }

    public function actionNotify(){
        $institution_code = \Yii::$app->request->get('institution_code');
        $institution = Institution::getInstitutionByCode($institution_code);

        $cmd = \Yii::$app->db->createCommand('select last_user_integral_record_id from t_temp_notify_institution where id=1');
//        $cmd->bindValue(':in_goods_code', $goodsCode);
//        $cmd->bindValue(':in_quantity', $quantity);


        $last_user_integral_record_id = $cmd->queryScalar();

        $cmd = \Yii::$app->db->createCommand('select t1.id,t2.integral,t2.phone from t_user_integral_record t1 left join t_user t2 on t1.user_id = t2.id where t1.create_datetime > (select create_datetime from t_user_integral_record where id=:id) order by t1.create_datetime');
        $cmd->bindValue(':id', $last_user_integral_record_id);

        $data = $cmd->queryAll();

        foreach ($data as $a){
            $re = Inteface::sendIntegraltoCqChianLife($a['phone'],$a['integral']);
            $cmd1 = \Yii::$app->db->createCommand('update t_temp_notify_institution set last_user_integral_record_id=:id where id=1');
            $cmd1->bindValue(':id',$a['id']);
            $r = $cmd1->execute();
            echo($a['id'].' ok ' .$re);
        }

        return $this->render('notify');
    }

//    public function actionError(){
//        return $this->render('error');
//    }

    public function actionFanso2o()
    {
//        $r = Fanso2oInteface::getActivityList(10, 1);
//        $r = Fanso2oInteface::getActivityInfo('d15c53299902452795895f66ada4baa5');
//        $r = Fanso2oInteface::getActivityResource('d15c53299902452795895f66ada4baa5');
//        $r =Fanso2oInteface::getCategoryTags(0);
//        $r = Fanso2oInteface::getCompanyInfo();
        $r = Fanso2oInteface::getResourceList();
//        echo $r[0]->description;
        var_dump($r);

//        $appKey = '3aabc24ded224c00b9018d9f79e5316b';
//        $appSecret = 't5M8IIgn';
//        $timestamp = time();
////        $timestamp = 1474624485;
//        $signature = Tools::desEncode(strtoupper(md5($appKey . $timestamp)), $appSecret, '52136585');
////        $signature = $this->encrypt1(md5($appKey . $timestamp), $appSecret);
//        var_dump($signature);

//        $url = "http://open.fanso2o.com/api/activity/list";
//        $data = [
//            'appKey' => $appKey,
//            'signature' => $signature,
//            'timestamp' => $timestamp
//        ];
//        $result = Tools::postJson($url, $data, true);

//        $postUrl = 'http://open.fanso2o.com/api/activity/list';
//        $postData = array(
//            'appKey' => $appKey,
//            'signature' => $signature,
//            'timestamp' => $timestamp
//        );
//
//        $r = Tools::postForm($postUrl, $postData);
//        var_dump($r);
    }

//    public function actionVoucherGen()
//    {
//        for ($i = 200; $i < 1000; $i++) {
//            $cmd = \Yii::$app->db->createCommand('insert into `t_voucher` ( id, `status`, `is_card`, `voucher`, `token`) values (:i,  0, 0, :i, :i);');
//            $cmd->bindValue(':i', $i);
//            $cmd->execute();
//        }
//    }
}
